<template>
  <base-modal
    :show.sync="visible"
    :title="$t('smartPlan.editName')"
    class="edit-plan-name-modal"
    width="500px"
  >
    <el-form
      ref="form"
      class="form-container"
      :rules="rules"
      label-position="top"
      :model="form"
    >
      <el-form-item :label="$t('task.edit.planName')" prop="planName">
        <el-input v-model="form.planName" :placeholder="t('common.placeholder.inputSomething', {data1: t('task.edit.planName')})"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="visible = false">{{ $t('common.base.cancel') }}</el-button>
      <el-button type="primary" @click="submit" :disabled="pending">{{$t('common.base.confirm')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
import { updatePlanName } from '@src/modules/smartPlan/api/index.js'
import { t } from '@src/locales'
export default {
  name: 'edit-plan-name-dialog',
  props: {
    planId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      visible: false,
      pending: false,
      form: {
        planName: ''
      },
      rules: {
        planName: [
          { required: true, message: t('common.placeholder.inputSomething', {data1: t('task.edit.planName')}), trigger: 'blur' },
          { max: 50, message: t('common.validate.nameLimit', {limit: 50}), trigger: 'blur' },
        ]
      }
    }
  },
  methods: {
    open(planName) {
      this.visible = true
      this.form.planName = planName
    },
    submit() {
      this.$refs.form.validate().then(valid => {
        if (valid) {
          this.pending = true
          updatePlanName({
            id: this.planId,
            planName: this.form.planName
          }).then(res => {
            this.pending = false
            let isSucc = res.success || res.succ;
          
            this.$platform.notification({
              type: isSucc ? 'success' : 'error',
              title: isSucc ? t('common.base.tip.modifySuccess') : t('common.base.tip.modifyFail'),
              message: !isSucc && res.message
            })
            // 修改成功更新详情的计划名称
            if (isSucc) {
              this.$emit('editPlanNameSuccess', this.form.planName)
              this.visible = false
            }
          })
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.form-container {
  padding: 24px;
}
</style>